﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;

namespace hzWeb.Layouts
{
    /// <summary>
    /// Call example: http://sharepoint2010/SDQ1E31Q/_layouts/hzWeb/GetLibraryTree.ashx?ListName=Documents
    /// http://api.jquery.com/jquery.ajax/
    /// </summary>
    public partial class GetLibraryTree : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string listName = context.Request.QueryString["ListName"];
            SPContext currentContext =  SPContext.Current;
            context.Response.ContentType = "application/json";
            System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            SPList lib = currentContext.Web.Lists[listName];
            SPFolder root = lib.RootFolder;

            LibraryTreeNode node = new LibraryTreeNode();
            node.title = "文档";
            node.key = "root";
            node.expand = true;
            node.children = new System.Collections.Generic.List<LibraryTreeNode>();
            BuildNode(root, node, lib);          

            string jsonResult = jsonSerializer.Serialize(node);
            context.Response.Write(jsonResult);
        }
        
        private void BuildNode(SPFolder parentFolder, LibraryTreeNode parentNode, SPList lib)
        {
            if (parentFolder.SubFolders.Count != 0)
            {
                foreach (SPFolder folder in parentFolder.SubFolders)
                {
                    if (parentFolder == lib.RootFolder && folder.Name == "Forms")
                    {
                        continue;
                    }

                    LibraryTreeNode node = new LibraryTreeNode();
                    node.key = folder.ServerRelativeUrl;                   
                    node.title = folder.Name;
                    // node.opened = true;
                    parentNode.children.Add(node);

                    if (folder.SubFolders.Count != 0)
                    {
                        node.children = new System.Collections.Generic.List<LibraryTreeNode>();
                        BuildNode(folder, node, lib);
                    }
                }
            }
        }
    }
}
